<?php

namespace App\Console\Commands;

use App\Models\Personnel\Personnel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class updatePersonnelPhoto extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update:photo';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新人员照片';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 行政
        $adminPath = public_path('storage/personnel/行政');
        $adminFiles = File::allFiles($adminPath);
        $adminFiles = $this->getFilesNamePath($adminFiles, '行政');
        $admin = Personnel::query()->where('type', 0)->get();
        $this->updatePersonPhoto($admin, $adminFiles);

        // 行政
        $driverPath = public_path('storage/personnel/驾驶员');
        $driverFiles = File::allFiles($driverPath);
        $driverFiles = $this->getFilesNamePath($driverFiles, '驾驶员');
        $driver = Personnel::query()->where('type', 1)->get();
        $this->updatePersonPhoto($driver, $driverFiles);
    }

    public function getFilesNamePath($files, $type)
    {
        $data = [];
        $basePath = config('app.url').'/storage/personnel/';
        foreach ($files as $k => $file) {
            $baseName = $file->getBasename();
            $data[] = [
                'name' => explode('.', $baseName)[0],
                'path' => $basePath.$type.'/'.$file->getFileName(),
            ];
        }

        return collect($data);
    }

    public function updatePersonPhoto($personnel, $files)
    {
        foreach ($personnel as $k => $person) {
            $photo = $files->where('name', $person->name)->first();
            if ($photo) {
                $person->update(['ID_photo_url' => $photo['path']]);
                $this->info("- Yes: {$photo['name']}");
            } else {
                $this->info("- No: {$person->name}");
            }
        }
    }
}
